import crypto from 'crypto';

/**
 * 生成创宇监测 API 请求 Token
 * @param {String} apiId -- 创宇监测 API_ID
 * @param {String} apiKey -- 创宇监测 API_KEY
 * @param {{ [k: String]: any }} params -- 请求参数
 * @return {String} 请求 Token
 */
export default function authHeaderBuilder(apiId, apiKey, params) {
	let paramsSorted = params.sort((a, b) => a[0].localeCompare(b[0]));
	paramsSorted = new URLSearchParams(paramsSorted).toString();
	paramsSorted = decodeURIComponent(paramsSorted);

	let token = crypto
		.createHmac('sha1', apiKey)
		.update(paramsSorted)
		.digest('hex');
	token = Buffer.from(`${apiId}:${token}`).toString('base64');

	return `Basic ${token}`;
}
